﻿using System;
using System.Web;
using System.Web.Caching;

namespace Utility
{
    public class CacheManager
    {
        private static readonly System.Web.Caching.Cache cache;
        static CacheManager()
        {
            HttpContext current = HttpContext.Current;
            if (current != null)
            {
                cache = current.Cache;
            }
            else
            {
                cache = System.Web.HttpRuntime.Cache;
            }
        }

        /// <summary>
        /// 不允许实例化本类的对象
        /// </summary>
        private CacheManager()
        {

        }

        /// <summary>
        /// 从指定的键名称中获取缓存对象
        /// </summary>
        /// <param name="key">缓存的键名称</param>
        /// <returns></returns>
        public static object Get(string key)
        {
            return cache[key];
        }
      
        /// <summary>   
        /// 添加缓存对象   
        /// </summary>   
        /// <param name="key">索引键值</param>   
        /// <param name="value">缓存对象</param>   
        /// <param name="dependencyKey">缓存依赖项</param> 
        public static void Add(string key, object value, string dependencyKey)
        {
            //if (string.IsNullOrEmpty(dependencyKey))//无依赖项
            //{
                cache.Insert(key, value, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            //}
            //else
            //{
            //    string[] relatedKeys = new string[1];
            //    relatedKeys[0] = dependencyKey;
            //    CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
            //    cache.Insert(key, value, keyDependency, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            //}
        }

        /// <summary>   
        /// 删除缓存对象   
        /// </summary>   
        /// <param name="key">索引键值</param>   
        public static void Remove(string key)
        {
            cache.Remove(key);
        }

        /// <summary>   
        /// 清空缓存   
        /// </summary>   
        public static void Clear(string guid)
        {
            System.Collections.IDictionaryEnumerator enumerator = cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Key.ToString().IndexOf(guid) != -1)
                {
                    cache.Remove(enumerator.Key.ToString());
                }
            }
        }
    }
}
